import { useRouter, useRoute } from 'vue-router';
import {
  deptTreeApi,
  qrcodeListApi,
  assetTypeListApi,
  manufacturerListApi,
  workshopSelectApi,
} from '@/utils/apiConfig';
import useUserStore from '@/store/modules/user';
export function getAvatarUrl(url: string): string {
  if (!url) return '';
  // 判断是否以 http 开头，不是则添加
  if (/^https?:\/\//i.test(url)) {
    return url.replace(/^http:/i, 'http:'); // 保留原样或替换为 http
  }
  return 'http://' + url;
}
export function downloadFile(url, fileName = '') {
  const eleLink = document.createElement('a');
  if (fileName) {
    eleLink.download = fileName;
  }
  eleLink.style.display = 'none';
  eleLink.href = url;
  // 受浏览器安全策略的因素，动态创建的元素必须添加到浏览器后才能实施点击
  document.body.appendChild(eleLink);
  // 触发点击
  eleLink.click();
  // 然后移除
  document.body.removeChild(eleLink);
}
/** vite的特殊性, 需要处理图片 */
export const requireImg = (imgPath: String) => {
  return new URL(`../assets/${imgPath}`, import.meta.url).href;
};

const getLoadedScripts = () => {
  if (!(window as any)._amap_loaded_scripts) {
    (window as any)._amap_loaded_scripts = new Set<string>();
  }
  return (window as any)._amap_loaded_scripts as Set<string>;
};
// 优化的脚本加载函数
function loadScript(src: string): Promise<void> {
  return new Promise((resolve, reject) => {
    const loadedScripts = getLoadedScripts();

    // 检查脚本是否已经加载过
    if (loadedScripts.has(src)) {
      console.log(`脚本 ${src} 已加载，跳过重复加载`);
      return resolve();
    }

    // 检查DOM中是否已存在该脚本
    const existingScript = document.querySelector(`script[src="${src}"]`);
    if (existingScript) {
      // 如果脚本已存在但可能尚未完成加载，等待其加载完成
      if (existingScript.getAttribute('data-loaded') === 'true') {
        loadedScripts.add(src);
        return resolve();
      }

      // 为已有但未加载完成的脚本添加事件监听
      const onLoad = () => {
        existingScript.setAttribute('data-loaded', 'true');
        loadedScripts.add(src);
        existingScript.removeEventListener('load', onLoad);
        existingScript.removeEventListener('error', onError);
        resolve();
      };

      const onError = (e: Event) => {
        existingScript.removeEventListener('load', onLoad);
        existingScript.removeEventListener('error', onError);
        reject(e);
      };

      existingScript.addEventListener('load', onLoad);
      existingScript.addEventListener('error', onError);
      return;
    }

    // 创建并加载新脚本
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = src;
    script.async = true; // 异步加载
    script.defer = true; // 延迟执行

    script.onload = () => {
      script.setAttribute('data-loaded', 'true');
      loadedScripts.add(src);
      resolve();
    };

    script.onerror = (e) => {
      reject(e);
    };

    document.head.appendChild(script);
  });
}
export async function initMaps(mapRef: any, map: any) {
  const AMAP_KEY =
    import.meta.env.VITE_AMAP_KEY || '77a7c37b7c94ea24032824d3149aa7d2';
  // 加载高德地图 JS API 和 UI 插件（与 index.html 保持一致版本）
  // 检查是否已经加载过AMap对象，避免重复加载脚本
  if (!(window as any).AMap) {
    await loadScript(`https://webapi.amap.com/maps?v=1.4.15&key=${AMAP_KEY}`);
  }

  if (!(window as any).AMapUI) {
    await loadScript('https://webapi.amap.com/ui/1.0/main.js?v=1.0.11');
  }

  const AMap = (window as any).AMap;
  if (!AMap) return;

  // 初始化地图：默认使用卫星图
  map = new AMap.Map(mapRef.value, {
    resizeEnable: true,
    viewMode: '3D',
    zoom: 13,
    center: [116.397428, 39.90923],
    layers: [new AMap.TileLayer.Satellite()],
  });

  // 添加工具条与图层切换控件
  AMap.plugin(['AMap.ToolBar', 'AMap.MapType'], function () {
    const toolBar = new AMap.ToolBar({
      position: 'LT',
      offset: new AMap.Pixel(10, 10),
    });
    map.addControl(toolBar);

    const mapType = new AMap.MapType({
      defaultType: 1,
      showRoad: false,
      position: 'RT',
    });
    map.addControl(mapType);
  });

  // 添加单个标记点
  const lng = 116.397428;
  const lat = 39.90923;
  const color = 'red';
  const assetId = `FT11233`;

  const marker = new AMap.Marker({
    position: [lng, lat],
    icon: new AMap.Icon({
      size: new AMap.Size(20, 20),
      image: `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="${color}"><circle cx="12" cy="12" r="10" stroke="black" stroke-width="1"/></svg>`,
      imageSize: new AMap.Size(20, 20),
    }),
    offset: new AMap.Pixel(-10, -10),
    title: `资产点位`,
  });

  marker.setMap(map);

  const infoWindow = new AMap.InfoWindow({
    content: `<div class="custom-info-window" style="color:#fff;">
                    <h3>资产详细信息</h3>
                    <p>ID：${assetId}</p>
                    <p>尺寸：75寸</p>
                    <p>位置: [${lng.toFixed(6)}, ${lat.toFixed(6)}]</p>
                    <p>资产类型：显示器</p>
                  </div>`,
    offset: new AMap.Pixel(0, -30),
  });

  marker.on('click', () => {
    infoWindow.open(map, marker.getPosition());
  });

  // 设置地图视野以显示该点
  map.setFitView([marker]);
}
/**
 * 判断是否是base64字符串
 *
 * @param {string} str
 * @return {boolean}
 */
export function isBtoa(str: string): boolean {
  try {
    const decoded = atob(str);
    for (let i = 0; i < decoded.length; i++) {
      if (decoded.charCodeAt(i) > 255) {
        return false;
      }
    }
    return true;
  } catch (e) {
    return false;
  }
}
export const getOtherQuery = () => {
  const route = useRoute();
  const query: any = route.query;
  if (query) {
    return Object.keys(query).reduce((acc, cur) => {
      if (cur !== 'redirect') {
        acc[cur] = query[cur];
      } else {
        redirect = query[cur];
      }

      return acc;
    }, {});
  }

  return {};
};

const userStore = useUserStore();
//获取部门
export function setDeptListVuex() {
  return new Promise((resolve) => {
    deptTreeApi({}).then((res) => {
      const treeData = res.data || [];
      // 同步到用户 store
      userStore.setDeptList(treeData);
      resolve(treeData);
    });
  });
}
export function setDeptFormatter() {
  const deptList = userStore.deptList;

  // 递归转换部门数据格式：deptName=>label, id=>value，并处理children
  function transformDeptData(data: any[]) {
    if (!Array.isArray(data)) return [];

    return data.map((item) => {
      const transformedItem = {
        ...item,
        label: item.deptName, // deptName 转换为 label
        value: item.deptNo, // id 转换为 value
      };

      // 递归处理children
      if (
        item.children &&
        Array.isArray(item.children) &&
        item.children.length > 0
      ) {
        transformedItem.children = transformDeptData(item.children);
      }

      return transformedItem;
    });
  }

  // 执行转换并返回转换后的数据
  return transformDeptData(deptList);
}

//获取二维码
export function setQrcodeListVuex() {
  return new Promise((resolve) => {
    qrcodeListApi({ page: 1, size: 1000, labelCode: '', status: 0 }).then(
      (res) => {
        const list = res.data.records || [];
        // 同步到用户 store
        console.log('获取二维码', list);
        userStore.setQrcodeList(list);
        resolve(list);
      }
    );
  });
}

//设备类型
export function setAssetTypeListVuex() {
  return new Promise((resolve) => {
    assetTypeListApi({ page: 1, size: 100, deviceName: '' }).then((res) => {
      const list = res.data.records || [];
      // 同步到用户 store
      console.log('设备类型', list);
      userStore.setAssetTypeList(list);
      resolve(list);
    });
  });
}

//生产厂家
export function setManufacturer() {
  return new Promise((resolve) => {
    manufacturerListApi({ page: 1, size: 100, manufacturerName: '' }).then(
      (res) => {
        const list = res.data.records || [];
        // 同步到用户 store
        userStore.setFactotyList(list);
        resolve(list);
      }
    );
  });
}
//厂房下拉
export function setWorkshopListVuex() {
  return new Promise((resolve) => {
    workshopSelectApi({}).then((res) => {
      const list = res.data || [];
      // 同步到用户 store
      console.log('厂房下拉', list);
      const work = list.map((item: any) => {
        return { label: item.name, value: item.id };
      });
      userStore.setWorkshopList(work);
      resolve(list);
    });
  });
}
export function getVuexList() {
  setDeptListVuex();
  setQrcodeListVuex();
  setAssetTypeListVuex();
  setManufacturer();
  setWorkshopListVuex();
}
